package io.renren.modules.health.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.health.dao.HmCustomerDao;
import io.renren.modules.health.dto.HmCustomerDTO;
import io.renren.modules.health.dto.LoginDTO;
import io.renren.modules.health.entity.HmCustomerEntity;
import io.renren.modules.health.entity.TokenEntity;
import io.renren.modules.health.service.HmCustomerService;
import io.renren.modules.health.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户信息表
 *
 * @author Mark 
 * @since 1.0.0 2024-03-29
 */
@Service
public class HmCustomerServiceImpl extends CrudServiceImpl<HmCustomerDao, HmCustomerEntity, HmCustomerDTO> implements HmCustomerService {

    @Autowired
    private TokenService tokenService;

    @Override
    public QueryWrapper<HmCustomerEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String phonenum = (String)params.get("phonenum");

        QueryWrapper<HmCustomerEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
        wrapper.eq(StrUtil.isNotBlank(phonenum), "phonenum", phonenum);

        return wrapper;
    }


    @Override
    public Map<String, Object> login(LoginDTO dto) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("newUser","0");
        HmCustomerEntity user = getByPhonenum(dto.getPhonenum());
        if (user == null) {
            user = new HmCustomerEntity();
            user.setPhonenum(dto.getPhonenum());
            user.setStatus(0);
            user.setCreateDate(new Date());
            baseDao.insert(user);
            map.put("newUser","1");
        }
        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getCusId());

        map.put("user", user);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());

        return map;
    }

    private HmCustomerEntity getByPhonenum(String phonenum) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("phonenum",phonenum);
        return baseDao.selectOne(getWrapper(param));
    }
}